package com.bbz.core.map;

import java.util.HashMap;
/**
 * 多线程下HashMap 线程不安全会导致死循环和获取不到value值
 * @author binbin.a.zhang
 *
 */
public class HashMapDemo {
	static HashMap<Integer, String> hashMap = new HashMap<>();

	public static void main(String args[]) {

		Thread thread = new Thread(new ThreadRunnable());
		thread.start();
		Thread thread1 = new Thread(new ThreadRunnable1());
		thread1.start();
		try {
			Thread.sleep(10000);
		} catch (InterruptedException e) {
			e.printStackTrace();
		}
		for (int i = 0; i < 10000; i++) {
			System.out.println(hashMap.get(i));
		}
	}

	static class ThreadRunnable implements Runnable {

		@Override
		public void run() {
			long startDate = System.currentTimeMillis();

			for (int i = 0; i < 1000000; i++) {
				hashMap.put(i, String.valueOf(i));
			}
			long endDate = System.currentTimeMillis();
			System.out.println(endDate - startDate);

		}

	}

	static class ThreadRunnable1 implements Runnable {

		@Override
		public void run() {
			long startDate = System.currentTimeMillis();

			for (int i = 1000000; i < 10000000; i++) {
				hashMap.put(i, String.valueOf(i));
			}
			long endDate = System.currentTimeMillis();
			System.out.println(endDate - startDate);

		}

	}
}
